package com.qfedu.openplateform.manager.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qfedu.openplateform.manager.entity.AjaxMessage;
import com.qfedu.openplateform.manager.entity.TableData;
import com.qfedu.openplateform.manager.entity.UserToken;
import com.qfedu.openplateform.manager.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/sys/token")
public class TokenController {


    @Autowired
    private TokenService tokenService;

    @RequestMapping("/table")
    public TableData findAllUserToken (String accessToken , int page, int limit) {

        PageHelper.startPage(page,limit);

        if (accessToken != null && accessToken != "") {
            List<UserToken> userToken = tokenService.findAllUserTokenByAccessToken(accessToken,page,limit);

            PageInfo pageInfo = new PageInfo(userToken);

            TableData<UserToken> tableData = new TableData<>();

            tableData.setCount(pageInfo.getTotal());
            tableData.setData(userToken);

            return tableData;
        }

        List<UserToken> userToken = tokenService.findAllUserToken(page,limit);

        PageInfo pageInfo = new PageInfo(userToken);

        TableData<UserToken> tableData = new TableData<>();

        tableData.setCount(pageInfo.getTotal());
        tableData.setData(userToken);

        return tableData;
    }


    @RequestMapping("/update")
    @ResponseBody
    public AjaxMessage updateUserToken (UserToken userToken) {

        int i = tokenService.updateUserTokenById(userToken);

        AjaxMessage result = new AjaxMessage();

        if (i > 0) {

            result.setStatus(true);
            return result;

        }else {

            result.setStatus(false);
            result.setMessage("更新失败");
            return result;

        }

    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }


    @RequestMapping("/del")
    public AjaxMessage deleteUserTokenById (Integer[] ids) {

        try {
            tokenService.deleteUserTokenById(ids);
            return new AjaxMessage(true);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxMessage(false, "删除失败");
        }
    }

}
